package shop.controller.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import shop.core.plugins.wxqrcode.JacksonUtils;
import shop.core.plugins.wxqrcode.SignUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @Description 接收微信服务器推送的消息与事件
 * @Author semstouch
 * @Date 2017/9/22
 **/
@Controller
@RequestMapping("/manage/wxmsg")
public class WxMessageController {
    protected static final Logger logger = LoggerFactory.getLogger(WxMessageController.class);
    /**
     * 校验信息是否是从微信服务器发出，处理消息
     * @param request
     * @throws IOException
     */
    @RequestMapping(value="/connect",method = {RequestMethod.GET})
    public void processPost(HttpServletRequest request, HttpServletResponse response)  throws IOException {
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if(SignUtil.checkSignature(signature, timestamp, nonce)){
                // 随机字符串
                String echostr = request.getParameter("echostr");
                logger.info("接入成功，echostr="+echostr);
                response.getWriter().write(echostr);
            }
    }
    /**
     * 校验信息是否是从微信服务器发出，处理消息
     * @throws IOException
     */
    @RequestMapping(value="/connect",method = {RequestMethod.POST})
    public void processPost( HttpServletResponse response,@RequestBody String requestBody)  throws IOException {
            logger.info("接收微信消息:"+requestBody);
            Map res=JacksonUtils.xmlToNormalObject(requestBody, Map.class);
            logger.info("接收微信消息类型:"+res.get("MsgType").toString());
            response.getWriter().write("success");

    }
}
